package com.example.myapplication.ui.fragment.project

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.bean.article.ArticleBean
import com.example.myapplication.bean.category.CategoryBean
import com.example.myapplication.dialog.OperationDialog
import com.example.myapplication.ui.adapter.ArticleAdapter
import com.kun.base.env.Env
import com.kun.base.ui.AbsBaseFragment
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_home.*

/**
 *项目文章的fragment
 *
 * @author : Kun
 * @date : 2021/6/16
 * @time : 11:01
 */
class ProjectArticleFragment private constructor() : AbsBaseFragment() {
    private var index = 1
    private lateinit var articleAdapter: ArticleAdapter

    private var categoryBean: CategoryBean? = null

    private lateinit var projectArticleViewModel: ProjectArticleViewModel

    companion object {
        fun getInstance(categoryBean: CategoryBean): ProjectArticleFragment {
            return ProjectArticleFragment().apply {
                arguments = Bundle().apply { putSerializable("categoryBean", categoryBean) }
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_project_article
    }

    override fun initViewModel() {
        projectArticleViewModel = getFragmentScopeViewModel(ProjectArticleViewModel::class.java)
        initCollectArticleResult()
        initAddCollectArticle()
        initDelCollectArticle()
    }

    override fun initView() {
        categoryBean = arguments!!.getSerializable("categoryBean") as CategoryBean

        refresh_layout!!.setRefreshHeader(ClassicsHeader(activity))

        articleAdapter = ArticleAdapter(R.layout.item_article, null)
        articleAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()

        recycler_view!!.layoutManager = LinearLayoutManager(activity)
        recycler_view!!.adapter = articleAdapter

        articleAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            index = 1
            getData()
        }

        articleAdapter.setOnItemClickListener { _, _, position ->
            //文章点击
            val articleBean = articleAdapter.getItem(position)
            startToWeb(articleBean.link, articleBean.title)
        }
        articleAdapter.setOnItemLongClickListener { _, _, position ->
            val articleBean = articleAdapter.getItem(position)
            showOperationDialog(articleBean)
            return@setOnItemLongClickListener true
        }
        articleAdapter.addChildClickViewIds(R.id.view_collect)
        articleAdapter.setOnItemChildClickListener { _, childView, position ->
            val articleBean = articleAdapter.getItem(position)
            if (childView.id == R.id.view_collect) {
                if (articleBean.collect) {
                    projectArticleViewModel.requestDelCollectArticle(articleBean.id)
                } else {
                    projectArticleViewModel.requestAddCollectArticle(articleBean.id)
                }
            }
        }
        getData()
    }

    /**
     * 加载文章列表
     */
    private fun getData() {
        projectArticleViewModel.requestArticleList(index, categoryBean!!.id)
    }

    /**
     *收藏文章列表接口返回结果
     */
    private fun initCollectArticleResult() {
        projectArticleViewModel.projectRequest.articleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                if (t.data!!.curPage == 1) {
                    articleAdapter.setList(t.data!!.datas)
                } else {
                    articleAdapter.addData(t.data!!.datas)
                }
                if (t.data!!.curPage >= t.data!!.pageCount) {
                    articleAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    articleAdapter.loadMoreModule.loadMoreComplete()
                }
            } else {
                articleAdapter.loadMoreModule.loadMoreComplete()
            }
            refresh_layout!!.finishRefresh()
        })
    }

    /**
     * 收藏文章接口回调
     */
    private fun initAddCollectArticle() {
        projectArticleViewModel.collectRequest.addArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = true
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 取消收藏文章接口回调
     */
    private fun initDelCollectArticle() {
        projectArticleViewModel.collectRequest.delArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = false
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 跳转到web页面
     */
    private fun startToWeb(linkUrl: String, title: String) {
        var url = linkUrl
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = Env.getDomain() + url
        }

        ARouter.getInstance().build(ARouterPath.WEB).withString("url", url)
            .withString("title", title).navigation()
    }

    /**
     * 显示操作弹窗
     */
    private fun showOperationDialog(articleBean: ArticleBean) {
        OperationDialog(activity!!).apply {
            addSelectItems("打开链接", if (articleBean.collect) "取消收藏" else "收藏")
            setOnSelectListener(object : OperationDialog.OnSelectListener {
                override fun onSelect(name: String, position: Int) {
                    if (position == 0) {
                        startToWeb(articleBean.link, articleBean.title)
                    } else {
                        if (articleBean.collect) {
                            projectArticleViewModel.requestDelCollectArticle(articleBean.id)
                        } else {
                            projectArticleViewModel.requestAddCollectArticle(articleBean.id)
                        }
                    }
                    dismiss()
                }
            })
        }.show()
    }

}